<template>
    <div>
        <!-- 不支持提示信息 -->
        <div v-if="!isOraySupported" style="margin-bottom: 16px;">
            <a-alert
                :message="unsupportedMessage"
                type="warning"
                show-icon
                style="margin-bottom: 16px;"
            />
        </div>

        <a-form-model :class="{ 'disabled-form': !isOraySupported }">
            <a-row :gutter="16">
                <a-col :span="18">
                    <a-form-model-item label="SN信息">
                        <a-input
                            v-model="form.sn"
                            placeholder="请获取设备SN串"
                            :disabled="!isOraySupported"
                        />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-button
                        type="primary"
                        block
                        :disabled="!isOraySupported"
                        :loading="loading.getSN"
                        @click="handleGetSN"
                    >
                        {{ loading.getSN ? '正在获取...' : '获取' }}
                    </a-button>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="18">
                    <a-form-model-item label="运行状态">
                        <a-input v-model="form.runStatus" :disabled="true" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-button 
                        block 
                        :disabled="!isOraySupported" 
                        :loading="loading.getStatus"
                        @click="handleGetStatus"
                    >
                        {{ loading.getStatus ? '正在获取...' : '获取' }}
                    </a-button>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="18">
                    <a-form-model-item label="重启状态">
                        <a-input
                            v-model="form.restartStatus"
                            :disabled="true"
                        />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-button 
                        block 
                        :disabled="!isOraySupported" 
                        :loading="loading.restart"
                        @click="handleRestart"
                    >
                        {{ loading.restart ? '正在重启...' : '重启' }}
                    </a-button>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="18">
                    <a-form-model-item label="重置状态">
                        <a-input v-model="form.resetStatus" :disabled="true" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-button 
                        block 
                        :disabled="!isOraySupported" 
                        :loading="loading.reset"
                        @click="handleReset"
                    >
                        {{ loading.reset ? '正在重置...' : '重置' }}
                    </a-button>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="18">
                    <a-form-model-item label="启动状态">
                        <a-input v-model="form.startStatus" :disabled="true" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-button 
                        block 
                        :disabled="!isOraySupported" 
                        :loading="loading.start"
                        @click="handleStart"
                    >
                        {{ loading.start ? '正在启动...' : '启动' }}
                    </a-button>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="18">
                    <a-form-model-item label="停止状态">
                        <a-input v-model="form.stopStatus" :disabled="true" />
                    </a-form-model-item>
                </a-col>
                <a-col :span="6">
                    <a-button 
                        block 
                        :disabled="!isOraySupported" 
                        :loading="loading.stop"
                        @click="handleStop"
                    >
                        {{ loading.stop ? '正在停止...' : '停止' }}
                    </a-button>
                </a-col>
            </a-row>
        </a-form-model>

        <p>
            获取SN成功后请前往
            <a href="https://b.oray.com/" target="_blank">https://b.oray.com/</a>
            登录并激活
        </p>

        <div style="text-align: center; margin-top: 16px;">
            <a-button
                type="primary"
                style="margin-right: 8px;"
                :disabled="!isOraySupported"
                :loading="loading.save"
                @click="handleSave"
            >
                {{ loading.save ? '正在保存...' : '保存SN' }}
            </a-button>
        </div>
    </div>
</template>

<script>
import { Button, message, Alert } from 'ant-design-vue'
import { mapGetters } from 'vuex'
import { SettingsTabManager } from '@/api/TabManager'
import { GATEWAY_CONFIGS } from '@/config/gateway-config'

export default {
    name: 'OrayConfig',
    components: {
        'a-button': Button,
        'a-alert': Alert
    },
    data() {
        return {
            settingsTabManager: new SettingsTabManager(),
            dataLoaded: false,
            form: {
                sn: '',
                runStatus: '',
                restartStatus: '',
                resetStatus: '',
                startStatus: '',
                stopStatus: ''
            },
            // 加载状态
            loading: {
                getSN: false,
                getStatus: false,
                restart: false,
                reset: false,
                start: false,
                stop: false,
                save: false
            }
        }
    },
    computed: {
        ...mapGetters('groupTree', ['deviceConnection', 'selectedDeviceInfo']),

        // 获取当前设备的更新模式
        currentDeviceUpdateMode() {
            if (!this.selectedDeviceInfo) {
                return null
            }

            // 根据设备类型获取updateMode
            const deviceType =
        this.selectedDeviceInfo.gatewayType ||
        this.selectedDeviceInfo.deviceType
            const config = GATEWAY_CONFIGS[deviceType]

            if (config && config.hardwareInfo && config.hardwareInfo.updateMode) {
                return config.hardwareInfo.updateMode
            }

            // 如果直接有updateMode属性，使用它
            if (this.selectedDeviceInfo.updateMode) {
                return this.selectedDeviceInfo.updateMode
            }

            return null
        },

        // 判断是否支持花生壳功能（只有ethernet模式支持）
        isOraySupported() {
            return this.currentDeviceUpdateMode === 'ethernet'
        },

        // 获取不支持的提示信息
        unsupportedMessage() {
            if (!this.selectedDeviceInfo) {
                return '请先选择一个设备'
            }

            if (!this.currentDeviceUpdateMode) {
                return '无法确定设备的更新模式'
            }

            return `当前设备更新模式为 ${this.currentDeviceUpdateMode}，花生壳功能仅支持 ethernet 模式的设备`
        }
    },
    mounted() {
        console.log('🚀 [OrayConfig] 组件 mounted')
    },
    methods: {
        
        getParams() {
            if (!this.deviceConnection.ipAddress || !this.deviceConnection.port) {
                message.error('请先在 "设备操作Tab" 中配置IP地址和端口')
                return
            }

            return {
                ip: this.deviceConnection.ipAddress,
                port: parseInt(this.deviceConnection.port)
            }
        },

        async handleGetSN() {
            if (this.loading.getSN) return
            
            try {
                this.loading.getSN = true
                const params = this.getParams()
                if (!params) {
                    return
                }

                console.log('🔄 [OrayConfig] 获取SN，使用连接信息:', params)
                const res = await this.settingsTabManager.getOraySN(
                    JSON.stringify(params)
                )

                if (res.code === 0) {
                    this.form.sn = JSON.parse(res.data).sn || res
                    message.success('获取SN成功')
                } else {
                    message.error('获取SN失败: ' + (res.msg || '未知错误'))    
                }
            } catch (error) {
                console.error('获取SN失败:', error)
                message.error('获取SN失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.getSN = false
            }
        },
        async handleGetStatus() {
            if (this.loading.getStatus) return
            
            try {
                this.loading.getStatus = true
                const params = this.getParams()
                if (!params) {
                    return
                }

                const res = await this.settingsTabManager.getOrayStatus(
                    JSON.stringify(params)
                )
                if (res.code === 0) {
                    this.form.runStatus = JSON.parse(res.data).status || res
                    message.success('获取运行状态成功')
                } else {
                    message.error('获取运行状态失败: ' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('获取运行状态失败:', error)
                message.error('获取运行状态失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.getStatus = false
            }
        },
        async handleRestart() {
            if (this.loading.restart) return
            
            try {
                this.loading.restart = true
                const params = this.getParams()
                if (!params) {
                    return
                }

                const res = await this.settingsTabManager.restartOray(
                    JSON.stringify(params)
                )
                if (res.code === 0) {
                    this.form.restartStatus = res.data ? '重启成功' : '重启失败'
                    message.success('重启操作成功')
                } else {
                    message.error('重启操作失败: ' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('重启失败:', error)
                message.error('重启失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.restart = false
            }
        },
        async handleReset() {
            if (this.loading.reset) return
            
            try {
                this.loading.reset = true
                const params = this.getParams()
                if (!params) {
                    return
                }

                const res = await this.settingsTabManager.resetOray(
                    JSON.stringify(params)
                )
                if (res.code === 0) {
                    this.form.resetStatus = res.data ? '重置成功' : '重置失败'
                    message.success('重置操作成功')
                } else {
                    message.error('重置操作失败: ' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('重置失败:', error)
                message.error('重置失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.reset = false
            }
        },
        async handleStart() {
            if (this.loading.start) return
            
            try {
                this.loading.start = true
                const params = this.getParams()
                if (!params) {
                    return
                }

                const res = await this.settingsTabManager.startOray(
                    JSON.stringify(params)
                )

                if (res.code === 0) {
                    this.form.startStatus = res.data ? '启动成功' : '启动失败'
                    message.success('启动操作成功')
                } else {
                    message.error('启动操作失败: ' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('启动失败:', error)
                message.error('启动失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.start = false
            }
        },
        async handleStop() {
            if (this.loading.stop) return
            
            try {
                this.loading.stop = true
                const params = this.getParams()
                if (!params) {
                    return
                }

                const res = await this.settingsTabManager.stopOray(
                    JSON.stringify(params)
                )

                if (res.code === 0) {
                    this.form.stopStatus = res.data ? '停止成功' : '停止失败'
                    message.success('停止操作成功')
                } else {
                    message.error('停止操作失败: ' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('停止失败:', error)
                message.error('停止失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.stop = false
            }
        },
        async handleSave() {
            if (this.loading.save) return

            try {
                this.loading.save = true

                // 提取form中的所有字段值
                const configData = {
                    sn: this.form.sn,
                    runStatus: this.form.runStatus,
                    restartStatus: this.form.restartStatus,
                    resetStatus: this.form.resetStatus,
                    startStatus: this.form.startStatus,
                    stopStatus: this.form.stopStatus
                }
                // 调用API保存配置
                await this.settingsTabManager.saveOrayConfig(
                    JSON.stringify(configData)
                )

                message.success('花生壳配置保存成功')
            } catch (error) {
                console.error('保存花生壳配置失败:', error)
                message.error('保存失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading.save = false
            }
        },

        // 更新数据的方法，供父组件调用
        updateData(settingsData) {
            console.log('🔄 [OrayConfig] 更新数据:', settingsData)

            if (!settingsData) {
                console.log('⚠️ [OrayConfig] 没有数据，跳过更新')
                return
            }

            try {
                // settingsData.data 是一个JSON字符串，需要解析
                const parsedData = JSON.parse(settingsData.data)

                // 使用 || 提供默认值，防止 undefined
                this.form.sn = parsedData.sn || ''
                this.form.runStatus = parsedData.runStatus || ''
                this.form.restartStatus = parsedData.restartStatus || ''
                this.form.resetStatus = parsedData.resetStatus || ''
                this.form.startStatus = parsedData.startStatus || ''
                this.form.stopStatus = parsedData.stopStatus || ''

                console.log('✅ [OrayConfig] 数据更新成功:', this.form)
                this.dataLoaded = true
            } catch (error) {
                console.error('❌ [OrayConfig] 数据更新失败:', error)
                this.$message.error('数据更新失败: ' + (error.message || '未知错误'))
            }
        },

        // 获取当前配置数据
        getCurrentConfig() {
            // 返回所有字段
            return {
                sn: this.form.sn,
                runStatus: this.form.runStatus,
                restartStatus: this.form.restartStatus,
                resetStatus: this.form.resetStatus,
                startStatus: this.form.startStatus,
                stopStatus: this.form.stopStatus
            }
        }
    }
}
</script>

<style scoped>
.ant-form-item {
    display: flex;
    align-items: center;
    margin-bottom: 0;
}
.ant-form-item >>> .ant-form-item-label {
    width: 80px;
    text-align: right;
}
.ant-form-item >>> .ant-form-item-control-wrapper {
    flex: 1;
}

/* 禁用状态的表单样式 */
.disabled-form {
    opacity: 0.6;
    pointer-events: none;
}
.disabled-form .ant-form-item {
    color: #999;
}
</style> 